﻿using NET6.WebAPI.Configs;
using NET6.WebAPI.Exceptions;
using System.Text;

namespace NET6.WebAPI.Extensions
{
    public static class HttpClientExtension
    {
        /*
         * 一言接口: https://v1.hitokoto.cn
         */

        /// <summary>
        /// 发送 GET 请求
        /// </summary>
        /// <param name="client"></param>
        /// <param name="url">请求路径(含参)</param>
        /// <returns></returns>
        public static async Task<string> SendGetRequestAsync(this HttpClient client, string? url)
        {
            if (url == null) return "请求路径是空的";

            try
            {
                var res = await client.GetAsync(url);
                res.EnsureSuccessStatusCode();

                return await res.Content.ReadAsStringAsync();
            }
            catch (Exception)
            {
                throw new ApiRequestException(url);
            }
        }

        /// <summary>
        /// 发送 POST 请求
        /// </summary>
        /// <param name="client"></param>
        /// <param name="url">请求路径</param>
        /// <returns></returns>
        public static async Task<string> SendPostRequestAsync(this HttpClient client, string? url)
        {
            if (url == null) return "请求路径是空的";

            try
            {
                var content = new StringContent(string.Empty);
                var res = await client.PostAsync(url, content);
                res.EnsureSuccessStatusCode();

                return await res.Content.ReadAsStringAsync();
            }
            catch (Exception)
            {
                throw new ApiRequestException(url);
            }
        }

        /// <summary>
        /// 发送 POST 请求(带参)
        /// </summary>
        /// <param name="client"></param>
        /// <param name="url">请求路径</param>
        /// <param name="obj">请求参数对象</param>
        /// <returns></returns>
        public static async Task<string> SendPostRequestAsync(this HttpClient client, string? url, object? obj)
        {
            if (url == null) return "请求路径是空的";

            try
            {
                var content = new StringContent(obj.ToJson(), Encoding.UTF8, ContentTypeConfig.Json);
                var res = await client.PostAsync(url, content);
                res.EnsureSuccessStatusCode();

                return await res.Content.ReadAsStringAsync();
            }
            catch (Exception)
            {
                throw new ApiRequestException(url);
            }
        }
    }
}
